package com.zhongxi.guoyuan.view.rewardCoin;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.shopCart.AddressListAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.shopcart.AddressListData;
import com.zhongxi.guoyuan.entity.shopcart.AddressListResult;
import com.zhongxi.guoyuan.url.Url;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/22.
 */

public class RewardAddressListActivity extends BaseActivity implements View.OnClickListener {
    public static final int RESULTCODEADDRESS = 99;
    public static final int REQUESTADDRESSCODE = 101;
    private PullToRefreshListView lvList;
    private List<AddressListData> list = new ArrayList<AddressListData>();
    private AddressListAdapter adapter;
    private String type;
    private TextView tvComplete;
    private TextView tvAdd;

    private Map<String, String> map = new HashMap<String, String>();

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pos = msg.what;
            deleteAddress();
        }
    };
    private AddressListResult result;
    private int pos;
    private String addressId;

    /**
     * 删除地址
     */
    private void deleteAddress() {
        type = "delete";
        map.clear();
        map.put("aid", result.getData().get(pos).getId());
        getServer(Url.REWARD_DELETE_ADDRESS, map, "", false, null, "post");
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_address_list);
        initTitle();
        tvTitle.setText("收货地址");
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        tvAdd = (TextView) findViewById(R.id.tvAdd);
        tvComplete = (TextView) findViewById(R.id.tvComplete);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new AddressListAdapter(this, list, handler);
        lvList.setAdapter(adapter);
        addressList();
    }

    /**
     * 获取地址列表
     */
    private void addressList() {
        type = "addresslist";
        getServer(Url.REWARD_ADDRESS_LIST, null, "", false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvAdd.setOnClickListener(this);
        tvComplete.setOnClickListener(this);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", list.get(i-1).getUsername()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", list.get(i-1).getId()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", list.get(i-1).getMphone()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", list.get(i-1).getProvince()
                        + list.get(i-1).getCity() + list.get(i-1).getPrefecture() + list.get(i-1).getAddress()).commit();
                setResult(RESULTCODEADDRESS);
                finish();
            }
        });
        lvList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                addressList();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                if (adapter != null && !"".equals(adapter)) {
                    if (adapter.getSelectPos() == -1) {
                        setResult(RESULTCODEADDRESS);
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
                    } else {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", list.get(adapter.getSelectPos()).getUsername()).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", list.get(adapter.getSelectPos()).getId()).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", list.get(adapter.getSelectPos()).getMphone()).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", list.get(adapter.getSelectPos()).getProvince()
                                + list.get(adapter.getSelectPos()).getCity() + list.get(adapter.getSelectPos()).getPrefecture() + list.get(adapter.getSelectPos()).getAddress()).commit();
                        setDefaultAddress();
                    }
                }
                finish();
                break;
            case R.id.tvAdd:
                Intent intent = new Intent(context, RewardEditAddressActivity.class);
                startActivityForResult(intent, REQUESTADDRESSCODE);
                break;
            case R.id.tvComplete:
                //设置默认地址
                if (adapter != null && !"".equals(adapter)) {
                    if (adapter.getSelectPos() != -1) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", list.get(adapter.getSelectPos()).getUsername()).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", list.get(adapter.getSelectPos()).getId()).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", list.get(adapter.getSelectPos()).getMphone()).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", list.get(adapter.getSelectPos()).getProvince()
                                + list.get(adapter.getSelectPos()).getCity() + list.get(adapter.getSelectPos()).getPrefecture() + list.get(adapter.getSelectPos()).getAddress()).commit();
                        setDefaultAddress();
                    } else {
                        showShortToast("请选择默认地址");
                    }
                } else {
                    showShortToast("请编辑添加地址");
                }
                break;
        }
    }

    /**
     * 上传默认配送地址
     */
    private void setDefaultAddress() {

        type = "default";
        String str = "&aid=" + list.get(adapter.getSelectPos()).getId();
        getServer(Url.SET_REWARD_DEFAULT_ADDRESS, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if ("addresslist".equals(type)) {
                result = gson.fromJson(response, AddressListResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                list.clear();
                if (null != result.getData() && result.getData().size() > 0) {
                    if (!TextUtils.isEmpty(addressId)) {
                        List<AddressListData> data = result.getData();
                        for (int i = 0; i < data.size(); i++) {
                            if (addressId.equals(data.get(i).getId())) {
                                data.get(i).setIsdefault("1");
                            } else {
                                data.get(i).setIsdefault("0");
                            }
                        }
                        list.addAll(data);
                    } else {
                        list.addAll(result.getData());
                    }
                } else {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            } else if ("default".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                finish();
            } else if ("delete".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if (pos == adapter.getSelectPos()) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
                }
                list.remove(pos);
                adapter.notifyDataSetChanged();
                showShortToast("删除地址成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        try {
            Gson gson = new Gson();
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (result.getCode()==1666){
                showShortToast("服务不可用，服务器异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTADDRESSCODE && resultCode == RewardEditAddressActivity.RESULTADDRESSCODE) {
            addressId = data.getStringExtra("addressId");
        }
        addressList();

    }

    @Override
    public void onBackPressed() {
        if (adapter != null && !"".equals(adapter)) {
            if (adapter.getSelectPos() == -1) {
                setResult(RESULTCODEADDRESS);
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            } else {
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", list.get(adapter.getSelectPos()).getUsername()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", list.get(adapter.getSelectPos()).getId()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", list.get(adapter.getSelectPos()).getMphone()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", list.get(adapter.getSelectPos()).getProvince()
                        + list.get(adapter.getSelectPos()).getCity() + list.get(adapter.getSelectPos()).getPrefecture() + list.get(adapter.getSelectPos()).getAddress()).commit();
                setDefaultAddress();
            }
        }
        super.onBackPressed();
    }
}
